<template>
  <div>
    <h3>比赛成绩统计</h3>
    <div class="container">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row type="flex" style="margin-bottom: 20px;" :gutter="20" justify="space-between">
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.matchYears" @change="matchYearsChange" multiple size="small" collapse-tags filterable clearable
                  placeholder="选择年份">
                  <el-option :label="item" :value="item" v-for="(item,index) in matchYearData" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.matchYears=matchYearData" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.sportIds" @change="sportChange" multiple size="small" collapse-tags filterable clearable
                  placeholder="选择运动项目">
                  <el-option :label="value" :value="key" v-for="(value,key,index) in dict_sport" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.sportIds=Object.keys(dict_sport)" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.matchEventId" multiple size="small" collapse-tags filterable clearable
                  placeholder="选择参赛项目">
                  <el-option :label="value" :value="key" v-for="(value,key,index) in dict_matchEvent" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.matchEventId=Object.keys(dict_matchEvent)" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.matchLevelIds" multiple size="small" collapse-tags filterable clearable
                  placeholder="选择赛事级别">
                  <el-option :label="value" :value="key" v-for="(value,key,index) in dict_matchLevel" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.matchLevelIds=Object.keys(dict_matchLevel)" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.matchKindIds" multiple size="small" collapse-tags filterable clearable
                  placeholder="选择赛事类别">
                  <el-option :label="value" :value="key" v-for="(value,key,index) in dict_matchKin" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.matchKindIds=Object.keys(dict_matchKin)" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.coachId" multiple size="small" collapse-tags filterable clearable
                  placeholder="选择教练">
                  <el-option :label="value" :value="key" v-for="(value,key,index) in dict_coach" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.coachId=Object.keys(dict_coach)" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" :gutter="10" justify="space-between">
            <el-col :span="5">
              <el-radio-group size="small" v-model="radio">
                <el-radio-button label="1">明细统计</el-radio-button>
                <el-radio-button label="2">按运动项目统计</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" icon="el-icon-download" size="small" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="small" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="xTable" border stripe show-footer max-height="600" highlight-hover-row class="mytable-footer"
        highlight-current-row highlight-hover-column highlight-current-column empty-text=" " :footer-cell-class-name="cellStyle"
        :custom-config="{checkMethod: checkColumnMethod}" :loading="loading" :footer-method="footerMethod"
        :merge-footer-items="mergeFooterItems" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="coachName" title="教练" footer-align="center" width="140" sortable ></vxe-table-column>
        <vxe-table-column field="sportName" title="运动项目" align="center" footer-align="center" width="80" sortable ></vxe-table-column>
        <vxe-table-column field="matchEventName" title="参赛项目" align="center" footer-align="center" width="80" sortable ></vxe-table-column>
        <vxe-table-column field="matchName" title="比赛名字" footer-align="center" width="200" sortable ></vxe-table-column>
        <vxe-table-column field="delegationName" title="组队" footer-align="center" width="100" sortable ></vxe-table-column>
        <vxe-table-column field="first" title="金牌" align="center" sortable></vxe-table-column>
        <vxe-table-column field="second" title="银牌" align="center" sortable></vxe-table-column>
        <vxe-table-column field="third" title="铜牌" align="center" sortable></vxe-table-column>
        <vxe-table-column field="fourth" title="第四名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="fifth" title="第五名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="sixth" title="第六名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="seventh" title="第七名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="eighth" title="第八名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="ninth" title="第九名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="tenth" title="第十名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="eleventh" title="第十一名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="twelfth" title="第十二名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="thirteenth" title="第十三名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="fourteenth" title="第十四名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="fifteenth" title="第十五名" align="center" sortable></vxe-table-column>
        <vxe-table-column field="participation" title="参赛资格" align="center" sortable></vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :page-sizes="pageSizeNum"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
  </div>
</template>

<script>
  import {
    coach_by_org,
    sport_by_org,
    match_event,
    match_level,
    match_kind,
  } from '@/api/dict.js'
  import {
    match_statistics_all
  } from '@/api/organization.js'
  export default {
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        pageSizeNum: [10, 20, 50, 100, {
          label: '全部数据',
          value: -1
        }],
        mergeFooterItems: [{
          row: 0,
          col: 0,
          rowspan: 0,
          colspan: 5
        }],
        loading: false,
        filterName: '',
        dict_coach: {},
        dict_sport: {},
        dict_matchLevel: {},
        dict_matchKin: {},
        dict_matchEvent: {},
        defaultSport: {},
        defaultMatchEvent: {},
        searchForm: {
          matchYears: [],
          matchLevelIds: [],
          matchKindIds: [],
          sportIds: [],
          matchEventId: [],
          coachId: [],
        },
        radio: 1,
        matchYearData: [
          '2010',
          '2011',
          '2012',
          '2013',
          '2014',
          '2015',
          '2016',
          '2017',
          '2018',
          '2019',
          '2020',
          '2021',
          '2022',
          '2023',
          '2024',
          '2025',
          '2026',
          '2027',
          '2028',
          '2029',
          '2030',
        ],
        search: false,
      }
    },
    created() {
      this.init_dict().then(() => {
        this.getMatchAll()
      })
    },
    watch: {
      radio(val) {
        if (val == 1) {
          this.getMatchAll()
          this.$refs.xTable.resetColumn()
        } else {
          this.filterSport()
        }
      },
      filterName(val) {
      	if(!val){
      	  this.page = {
      	  currentPage: 1,
      	  pageSize: 10,
      	  totalResult: 0,
      	  }
      	  this.search = false
      	  this.findList()
      	}
      }
    },
    methods: {
      sportChange(val) {
        if(val && val.length!=0){
          let data = {}
          if(this.searchForm.matchYears.length!=0) data.matchYears = this.searchForm.matchYears.join(',')
          data.sportIds = val.join(',')
          match_statistics_all(data).then(res => {
            if (res.code === 200 && res.data.length != 0) {
              let obj = {}
              res.data.forEach(item=>{
                for(let key in this.defaultMatchEvent){
                  if(item.matchEventName == this.defaultMatchEvent[key]){
                    obj[key] = this.defaultMatchEvent[key]
                  }
                }
              })
              this.dict_matchEvent = obj
            } else {
              this.dict_matchEvent = {}
            }
          })
        }
      },
      matchYearsChange(val) {
        if(val && val.length!=0){
          let data = {}
          data.matchYears = val.join(',')
          match_statistics_all(data).then(res => {
            if (res.code === 200 && res.data.length != 0) {
              let obj1 = {}
              let obj2 = {}
              res.data.forEach(item=>{
                for(let key in this.defaultSport){
                  if(item.sportName == this.defaultSport[key]){
                    obj1[key] = this.defaultSport[key]
                  }
                  if(item.matchEventName == this.defaultMatchEvent[key]){
                    obj2[key] = this.defaultMatchEvent[key]
                  }
                }
              })
              this.dict_sport = obj1
              this.dict_matchEvent = obj2
            } else {
              this.dict_sport = {}
              this.dict_matchEvent = {}
            }
          })
        }
      },
      searchSubmit() {
        let data = {}
        if(this.searchForm.matchYears.length!=0)  data.matchYears = this.searchForm.matchYears.join(',')
        if(this.searchForm.matchLevelIds.length!=0) data.matchLevelIds = this.searchForm.matchLevelIds.join(',')
        if(this.searchForm.matchKindIds.length!=0) data.matchKindIds = this.searchForm.matchKindIds.join(',')
        if(this.searchForm.sportIds.length!=0) data.sportIds = this.searchForm.sportIds.join(',')
        if(this.searchForm.matchEventId.length!=0) data.matchEventId = this.searchForm.matchEventId.join(',')
        if(this.searchForm.coachId.length!=0) data.coachId = this.searchForm.coachId.join(',')
        match_statistics_all(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          matchYears: [],
          matchLevelIds: [],
          matchKindIds: [],
          sportIds: [],
          matchEventId: [],
          coachId: [],
        }
        this.dict_sport = this.defaultSport
        this.dict_matchEvent = this.defaultMatchEvent
        this.getMatchAll()
      },
      exportData() {
        this.$refs.xTable.exportData({
          filename: this.$route.meta.title, type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>比赛成绩统计表</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.xTable.print({
            sheetName: '比赛成绩统计表',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      filterSport() {
        let sumArr = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth',
          'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'participation',
        ]
        var arry = this.defaultDataList
        var temp = {};
        var newfood = []
        for (var i in arry) {
          var key = arry[i].sportName;
          if (temp[key]) {
            temp[key].sportName = temp[key].sportName;
            temp[key].coachName = temp[key].coachName;
            temp[key].matchEventName = temp[key].matchEventName;
            temp[key].matchName = temp[key].matchName;
            temp[key].delegationName = temp[key].delegationName;
            // temp[key].first = temp[key].first+ parseInt(arry[i].first);
            sumArr.forEach(sum => {
              temp[key][sum] = temp[key][sum] + parseInt(arry[i][sum]);
            })
          } else {
            temp[key] = {};
            temp[key].sportName = arry[i].sportName;
            temp[key].coachName = arry[i].coachName;
            temp[key].matchEventName = arry[i].matchEventName;
            temp[key].matchName = arry[i].matchName;
            temp[key].delegationName = arry[i].delegationName;
            // temp[key].first = parseInt(arry[i].first);
            sumArr.forEach(sum => {
              temp[key][sum] = parseInt(arry[i][sum]);
            })
          }
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.defaultDataList = newfood
        this.findList()
        this.$refs.xTable.hideColumn(this.$refs.xTable.getColumnByField('coachName'))
        this.$refs.xTable.hideColumn(this.$refs.xTable.getColumnByField('matchEventName'))
        this.$refs.xTable.hideColumn(this.$refs.xTable.getColumnByField('matchName'))
        this.$refs.xTable.hideColumn(this.$refs.xTable.getColumnByField('delegationName'))
      },
      checkColumnMethod({
        column
      }) {
        if (column.property === 'sportName') {
          return false
        }
        return true
      },
      sumNum(list, field) {
        let count = 0
        list.forEach(item => {
          count += Number(item[field])
        })
        return count
      },
      footerMethod({
        columns,
        data
      }) {
        const footerData = [
          columns.map((column, _columnIndex) => {
            if (_columnIndex === 0) {
              return '统计'
            }
            let sumArr = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
              'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'participation'
            ]
            if (sumArr.includes(column.property)) {
              let sum = []
              sum.push(this.sumNum(data, column.property))
              return sum
            }
            return ''
          }),
        ]
        return footerData
      },
      cellStyle({ $rowIndex, column }) {
        if($rowIndex === 0){
          return 'footer-style'
        }
      },
      getMatchAll() {
        match_statistics_all().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          if (item.coaches) {
            let coachesArr = item.coaches.split(',')
            let arr = []
            coachesArr.forEach(coache => {
              arr.push(this.dict_coach[coache])
            })
            item.coachName = arr.join(',')
          }
        })
        this.pageSizeNum[4].value = data.length
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          sport_by_org().then(res => {
            this.dict_sport = res
            this.defaultSport = res
          })
          coach_by_org().then(res => {
            this.dict_coach = res
          })
          match_event().then(res => {
            this.dict_matchEvent = res
            this.defaultMatchEvent = res
          })
          match_level().then(res => {
            this.dict_matchLevel = res
          })
          match_kind().then(res => {
            this.dict_matchKin = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
        this.mergeFooterItems = [{
          row: 0,
          col: 0,
          rowspan: 0,
          colspan: 5
        }]
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
          if (this.radio != 2) {
            this.mergeFooterItems = [{
              row: 0,
              col: 0,
              rowspan: 0,
              colspan: 5
            }]
          }
          this.$el.querySelector('.vxe-table--header-wrapper').after(this.$el.querySelector('.vxe-table--footer-wrapper'))
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    background-color: #FFFFFF;
    padding: 10px;
  }
</style>
